let express = require('express') , 
	app = express() , 
	server = require('http').createServer(app) , 
	WebSocketServer = require('ws').Server , 
	users = [] ; //当前在线的用户
server.listen(3000);

// 创建一个WebScoketServer
var wss = new WebSocketServer({
    server: server , 
    verifyClient: socketVerify //可选，验证连接函数  
});
// 把wss对象挂载到server上方便读取
app.wss = wss;
// 把users挂在到server
app.users = users;


var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/online', function(req, res, next) {
	res.json(success(app.users.length));
});

app.post('/login' , function(req , res , next){
	find = false;
	if (!req.body) {
		res.json(errorFunc('请输入昵称'));
		return;
	}
	app.users.forEach((item) => {
		if(item.nickname.toLocaleLowerCase() == req.body.name.toLocaleLowerCase() && !find){
			find = true;
		}
	})
	if (find) {
		res.json(errorFunc('昵称已被使用'));
	}else{
		res.json(success(null , '登录成功'));
	}
})

function socketVerify(info){
	// console.log(info);
	return true;// true 为允许连接，false 为拒绝连接
}

function success(data , msg){
	data = {
		code : 200 , 
		data : data , 
		msg : msg , 
	};
	return data
}

function errorFunc(data){
	data = {
		code : 404 , 
		msg : data , 
	};
	return data
}

function packs(data , type , item , other){
	// 向所有用户发送数据
	var returnJson = {
		data : data , 
		type : type
	};
	if (item) {
		returnJson = Object.assign(returnJson , {nickname : item.nickname , time : item.time})
	}
	if (other) {
		returnJson = Object.assign(returnJson , other)
	}
	return returnJson;
}

//广播  
wss.broadcast = function broadcast(s , ws) {  
    wss.clients.forEach(function each(client , index) {   
    	var returnJson = JSON.stringify(ws);
		client.send(returnJson);
    });
};

wss.on('connection', (wsConnect) => {
	// 收到消息
	wsConnect.on('message', (message) => {
		var data = JSON.parse(message);
		switch(data.type){
			case 'login' : 
				users.push({nickname : data.data , length : users.length});
				wss.userIndex = users.length;
				wss.userNickname = data.data;
				// 向所有用户发送数据
				wss.broadcast(1 , packs(data.data + '加入了聊天室' , 'system' , data , {count : users.length}));
				break;
			case 'logout' : 
				wsConnect.close();
				break;
			case 'normal' : 
				// 向所有用户发送数据
				wss.broadcast(1 , packs(data.data , 'normal' , data));
				break;
			default : 
				console.log(data);
				break;
		}
	});

	// 退出聊天  
	wsConnect.on('close', function(close) {  
		try{
			// 向所有用户发送数据
			users.splice(wss.userIndex - 1 , 1);
			console.log('离线了' , wss.userNickname);
			wss.broadcast(0 , packs(wss.userNickname + '退出了聊天室' , 'system' , null , {count : users.length}));
		}catch(e){
			console.log('刷新页面了');  
		}
	});
});